import {version} from './package.json';
import capture from "./lib/capture";
import storage from './lib/storage';
import request from "./lib/request";
import queue from "./lib/queue";
import {defaultInfo} from './config/index';
import {deepCopy} from "./utils";

window.log = (function () {

    //初始化
    function log_init(params) {

        if (JSON.stringify(storage.config_info) !== "{}") {
            return console.error("【log.js】log has been initialized and cannot be reconfigured.");
        }
        let tempParams = parameter_correction(params);
        storage.save("config_info", tempParams);

        capture.start_all();
        request.init_all();
        queue.loop();
    }

    //配置项校正
    function parameter_correction(params){
        if(!params) return defaultInfo;

        let tempObj = deepCopy(defaultInfo);
        Object.assign(tempObj, storage.config_info);
        Object.assign(tempObj, params);

        //校正采集度
        if(tempObj && typeof tempObj.degree === 'number'){
            if(tempObj.degree > 1){
                tempObj.degree = 1;
            }
            if(tempObj.degree < 0){
                tempObj.degree = 0;
            }
        }

        //校正进入类型
        if(tempObj && tempObj.pattern){
            tempObj.pattern = 'config';
        }

        return tempObj;
    }

    //重新调整初始化参数
    function log_setOptions(params) {

        if (!params) {
            return console.error("【log.js】Please set options.");
        }

        if (JSON.stringify(storage.config_info) === "{}") {
            return console.error("【log.js】Please use first log.init()");
        }

        let finalParams = parameter_correction(params);
        storage.save("config_info", finalParams);

        queue.shutdown();
        capture.start_all();
        request.init_all();
        queue.loop();
    }

    //获取终端信息
    function get_terminal_info() {
        return deepCopy(storage.terminal_info);
    }

    //获取性能信息
    function get_performance_info() {
        return deepCopy(storage.performance_info);
    }

    return {
        init: log_init,
        setOptions: log_setOptions,
        getTerminalInfo: get_terminal_info,
        getPerformanceInfo: get_performance_info,
        log: capture.diy_log,
        version: version
    };
})();